package com.streamer.app

import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Color
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.Toast

import com.google.android.material.button.MaterialButton
import com.google.android.material.textfield.TextInputEditText
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.streamer.app.utils.DialogUtils
import com.streamer.app.utils.SPUtils
import com.streamer.app.utils.UserManager
import com.streamer.app.utils.UserManager.saveUserInfo
import com.streamer.app.utils.api.ViewModel
import com.streamer.app.utils.http.Contacts
import com.streamer.app.utils.http.Contacts.Companion.KEY_USER_CODE
import com.streamer.app.utils.http.Contacts.Companion.KEY_USER_TOKEN
import kotlinx.coroutines.*

class LoginActivity : BaseActivity() {

    private lateinit var etParticipationCode: EditText
    private lateinit var etUserNickname: EditText
    private lateinit var btnLogin: MaterialButton
    private lateinit var cbAgreement: ImageView
    private lateinit var tvAgreement: TextView
    private var mParticipationCode = ""
    private var mPNickname = ""
    private var viewMode = ViewModel()
    private var isSelectFLag = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        // 使用UserManager检查登录状态

        initViews()
        setupListeners()
    }

    private fun initViews() {
        val fullText = "我已认真阅读、并同意《隐私协议》和《用户协议》"
        val spannableString = SpannableStringBuilder(fullText)
        var code = SPUtils.getInstance().getString(KEY_USER_CODE)

        etParticipationCode = findViewById(R.id.et_participation_code)
        etUserNickname = findViewById(R.id.et_user_nickname)
        btnLogin = findViewById(R.id.btn_login)
        cbAgreement = findViewById(R.id.cb_agreement)
        tvAgreement = findViewById(R.id.tvAgreement)
        if (code.isNotEmpty()
        ) {
            etParticipationCode.setText(code.toString())
        }
        // 设置"《隐私协议》"的点击事件和颜色
        val privacyStart = fullText.indexOf("《隐私协议》")
        val privacyEnd = privacyStart + "《隐私协议》".length
        spannableString.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
                // 处理"隐私协议"的点击事件
                val intent = Intent(this@LoginActivity, WebViewActivity::class.java)
                intent.putExtra("type", 1)
                startActivity(intent)

            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color = Color.parseColor("#067DCE") // 设置文字颜色
                ds.isUnderlineText = false // 去掉下划线
            }
        }, privacyStart, privacyEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

// 设置"《用户协议》"的点击事件和颜色
        val userStart = fullText.indexOf("《用户协议》")
        val userEnd = userStart + "《用户协议》".length
        spannableString.setSpan(object : ClickableSpan() {
            override fun onClick(widget: View) {
                // 处理"用户协议"的点击事件
                val intent = Intent(this@LoginActivity, WebViewActivity::class.java)
                intent.putExtra("type", 2)
                startActivity(intent)
            }

            override fun updateDrawState(ds: TextPaint) {
                super.updateDrawState(ds)
                ds.color = Color.parseColor("#067DCE") // 设置文字颜色
                ds.isUnderlineText = false // 去掉下划线
            }
        }, userStart, userEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)

        // 应用样式并设置点击事件生效
        tvAgreement.text = spannableString
        tvAgreement.movementMethod = LinkMovementMethod.getInstance()
        tvAgreement.highlightColor = Color.TRANSPARENT // 去掉点击时的背景高亮

        // 使用SPUtils统一管理数据
        viewMode.LoginLV.observe(this@LoginActivity) {

            if (it != null) {
                viewMode.info()
                viewMode.UserInfoLV.observe(this@LoginActivity) {
                    if (it != null) {
                        saveUserInfo(it)
                    }
                }

                if (!SPUtils.getInstance().getBoolean(Contacts.KEY_USER_ISSECONFIRM, false)) {
                    SPUtils.getInstance().put(Contacts.KEY_USER_ISSECONFIRM, true, true)
                }
                viewMode.getLiveInfo()
                // 使用SPUtils保存token，确保数据一致性
                SPUtils.getInstance().put(Contacts.KEY_USER_TOKEN, it?.access_token, true)
                SPUtils.getInstance().put(Contacts.KEY_USER_CODE, mParticipationCode, true)
            } else {

                DialogUtils.showConfirmLoginConfirmDialog(
                    this@LoginActivity, {
                        viewMode.login(
                            mParticipationCode, mPNickname, true
                        )
                        btnLogin.isEnabled = true
                        btnLogin.text = "登录"
                    })
            }

        }
        //判断开播的直播属于什么类型
        viewMode.LiveInfoLV.observe(this@LoginActivity) {
            if (it != null) {
                if (it.viewingTemplate == 2) {
                    val intent = Intent(this@LoginActivity, LiveStreamActivity::class.java)
                    startActivity(intent)
                    finish()
                } else if (it.viewingTemplate == 1) {
                    val intent = Intent(this@LoginActivity, ThreePaneLiveActivity::class.java)
                    startActivity(intent)
                    finish()
                } else if (it.viewingTemplate == 3) {
                    val intent = Intent(this@LoginActivity, ThreeScreenLiveActivity::class.java)
                    startActivity(intent)
                    finish()
                }

            }
        }
        cbAgreement.setOnClickListener {
            if (!isSelectFLag) {
                isSelectFLag = true
                cbAgreement.apply {
                    Glide.with(this).load(R.drawable.select_on_icon).into(this)
                }
            } else {
                isSelectFLag = false
                cbAgreement.apply {
                    Glide.with(this).load(R.drawable.select_off_icon).into(this)
                }
            }
        }
    }

    private fun setupListeners() {
        btnLogin.setOnClickListener {
            // 登录成功，跳转到主页

            mParticipationCode = etParticipationCode.text.toString()
            mPNickname = etUserNickname.text.toString()

            if (mParticipationCode.isBlank()) {
                Toast.makeText(this, "请输入参加码", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            if (mPNickname.isBlank()) {
                Toast.makeText(this, "请输入用户昵称", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            if (!isSelectFLag) {
                Toast.makeText(this, "请勾选隐私协议", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            // 检查协议是否同意（这里简化处理，实际应该根据ImageView的状态判断）
            // 暂时跳过协议检查，直接允许登录

            // 模拟登录过程
            btnLogin.isEnabled = false
            btnLogin.text = "登录中..."

            // 使用SPUtils获取数据
            viewMode.login(
                mParticipationCode, mPNickname, false
            )
            btnLogin.isEnabled = true
            btnLogin.text = "登录"
        }
    }


} 